<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applicant">
            <UserSelect v-model="form.applicant" :placeholder="$t('申请人')" @change="changeName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applicationTime">
            <DatePicker v-model="form.applicationTime" :placeholder="$t('申请时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('部门名称')" prop="deptId">
            <DeptSelect v-model="form.deptId" :placeholder="$t('部门名称')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系电话')" prop="phone">
            <el-input v-model="form.phone" :placeholder="$t('联系电话')" disabled show-word-limit maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('岗位/职务')" prop="postIds">
            <el-select v-model="form.postIds" multiple :placeholder="$t('请选择')" disabled>
              <el-option
                v-for="item in postOptions"
                :key="item.postId"
                :label="$t(item.postName)"
                :value="item.postId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('通知人员')" prop="noticeUsers">
            <UserSelect v-model="form.noticeUsers" multiple :placeholder="$t('通知人员')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('休假时间')" prop="dateRange">
            <DatePicker
              v-model="form.dateRange"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :default-time="['9:00:00', '18:00:00']"
              :pick-options="pickOptions"
              @change="vacationDays"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('工作交接人')" prop="workUser">
            <UserSelect v-model="form.workUser" :placeholder="$t('工作交接人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请休假天数')" prop="vacationDay">
            <el-input v-model="form.vacationDay" :placeholder="$t('申请休假天数')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('去除节假日休假天数')" prop="removeHoliday">
            <el-input v-model="form.removeHoliday" :placeholder="$t('去除节假日休假天数')" show-word-limit />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('休假明细') }}</span>
      </div>
      <el-table :data="form.oaVacationDetails" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('申请休假类型')" align="center" prop="vacationType">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('申请休假类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaVacationDetails.' + scope.$index + '.vacationType'" :rules="[{ required: true, message: $t('必填信息'), trigger: 'blur' }]">
              <el-select v-model="scope.row.vacationType" @change="vacationTypeChange(scope.row)">
                <el-option
                  v-for="(ele, index) in vacationTypeOptions"
                  :key="index"
                  :value="ele.id"
                  :label="$t(ele.type)"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('实际剩余天数')" align="center" prop="remainDay">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remainDay" disabled />
          </template>
        </el-table-column>
        <el-table-column :label="$t('本次申请天数')" align="center" prop="vacationDay">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('本次申请天数') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaVacationDetails.' + scope.$index + '.vacationDay'" :rules="[{ required: true, message: $t('必填信息'), trigger: 'blur' }]">
              <el-input-number v-model="scope.row.vacationDay" :controls="false" :precision="1" :placeholder="$t('本次申请天数')" @change="vacationDayChange(scope.row)" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="80">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:vacation:remove']" size="mini" type="text" icon="el-icon-delete" @click="delVacationDetails(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button v-if="!otherBtnHide" v-hasPermi="['oa:vacation:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addVacationDetails">{{ $t("添加") }}</el-button>
      </div>
      <FileTable :list.sync="form.fileList" data-type="oa_vacation" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:vacation" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
    import { saveOaVacation, getOaVacation, countSurplusDay, vacationDay } from '@/api/oa/vacation/vacation/oaVacation'
    import { findAll } from '@/api/oa/vacation/type/oaVacationType'
    import { getUser } from '@/api/system/user'
    import { listPost } from '@/api/system/post'
    export default {
      components: {
      },
        data() {
            return {
                // 菜单标识
                menuKey: 'oa_vacation',
                // 表单参数
                form: {
                  oaVacationDetails: [],
                  dateRange: []
                },
                pickOptions: {
                  disabledDate(time) {
                    return time.getTime() > Date.now()
                  }
                },
                // 表单校验
                rules: {
                  applicant: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], applicationTime: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], dateRange: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 休假类型
                vacationTypeOptions: [],
              postOptions: []
            }
        },
        created() {
            this.$bus.$emit('async_done')
          listPost({}).then(res => {
            this.postOptions = res.rows
          })
            findAll().then(response => {
              this.vacationTypeOptions = response.data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
              this.form.dateRange = []
                if (data != null && data.id !== undefined) {
                    getOaVacation(data.id).then(response => {
                        this.form = response.data
                      this.form.dateRange = []
                        this.$set(this.form.dateRange, 0, response.data.startDate)
                        this.$set(this.form.dateRange, 1, response.data.endDate)
                        this.loading = false
                    })
                } else {
                    this.reset()
                  this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                applicant: undefined,
                applicationTime: this.parseTime(new Date()),
                deptId: undefined,
                phone: undefined,
                startDate: undefined,
                endDate: undefined,
                vacationDay: undefined,
                removeHoliday: undefined,
                workUser: undefined,
                noticeUsers: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                fileList: [],
                dateRange: [],
                oaVacationDetails: []
                }
                this.form.dateRange = []
              // getUserProfile().then(response => {
              //   this.form.applicant = response.data.id
              //   this.form.deptName = response.data.dept.deptName
              //   this.form.deptId = response.data.dept.id
              //   this.form.phone = response.data.phonenumber
              //   this.loading = false
              // })
              this.form.applicant = this.$store.state.user.userId
              this.changeName()
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              if (this.form.dateRange === undefined || this.form.dateRange === null || this.form.dateRange === '' || this.form.dateRange === [] || this.form.dateRange.length === 0) {
                this.$refs['form'].validate()
                return this.msgError(this.$t('休假时间不能为空'))
              }
                if (this.form.oaVacationDetails === undefined || this.form.oaVacationDetails.length === 0) {
                  this.msgError(this.$t('休假明细总天数和去除节假日总天数不相等'))
                  return
                }
                let totalDay = 0
                for (let i = 0; i < this.form.oaVacationDetails.length; i++) {
                  if (!this.vacationDayChange(this.form.oaVacationDetails[i])) {
                    return
                  }
                  totalDay += Number(this.form.oaVacationDetails[i].vacationDay)
                }
                if (totalDay !== Number(this.form.removeHoliday)) {
                  this.msgError(this.$t('休假明细总天数和去除节假日总天数不相等'))
                  return
                }
                return new Promise((resolve, reject) => {
                  this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                      // 弹出遮罩层
                      this.loading = true
                      if (this.form.dateRange && this.form.dateRange.length > 0) {
                        this.form.startDate = this.form.dateRange[0] + ':00'
                        this.form.endDate = this.form.dateRange[1] + ':00'
                      }
                      // 保存数据
                      saveOaVacation(this.form).then(response => {
                        if (response.code === 200) {
                          // 点击的按钮是保存并启动流程
                          if (type === 'process') {
                            // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                            this.form.id = response.data.id
                            // 启动流程
                            this.startProcess(response.data.id)
                            // 点击的仅保存
                          } else {
                            this.msgSuccess(this.$t('保存成功'))
                            // 关闭form页面
                            this.closeForm()
                            resolve()
                          }
                        } else {
                          reject()
                          this.msgError(response.msg)
                          this.loading = false
                        }
                      }).catch(() => {
                        this.loading = false
                      })
                    } else {
                      reject()
                      this.locationError(document)
                    }
                  })
                })
           },
            // 启动流程
           startProcess: function(dataId) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = this.form.actTitle
               // 业务表名
               processData.dataTable = 'oa_vacation'
               // 业务ID
               processData.dataId = dataId
               // 申请人ID
               processData.applyUserId = this.form.applicant
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/oa/vacation/vacation/oaVacationForm'
               processData.viewPath = '@/views/oa/vacation/vacation/oaVacationView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // 计算开始时间和结束时间相差天数
          vacationDays(val) {
            // var startDate = new Date(this.form.startDate)
            // var endDate = new Date(this.form.endDate)
            /* var result = 0
            var diff = Math.abs(startDate.getTime() - endDate.getTime())
            var hour = Math.floor(diff / (1000 * 60 * 60))
            var day = Math.floor(diff / (1000 * 60 * 60 * 24))
            result = day
            if (day > 0) {
              hour -= day * 24
            }
            if (hour > 4) {
              // 如果大于半天(5小时)
              result += 0.5
              hour = Math.floor((diff - (day * 24 + 4) * 1000 * 60 * 60) / (1000 * 60 * 60))
            }
            if (hour >= 1) {
              result += 0.5
            } */
            // var result = parseInt(diff / (1000 * 60 * 60 * 24))
            this.form.oaVacationDetails.splice(0, this.form.oaVacationDetails.length)
            const date = {
              startDate: val[0] + ':00',
              endDate: val[1] + ':00'
            }
            countSurplusDay(date).then(response => {
              this.form.vacationDay = response.data.totalDay
              this.form.removeHoliday = response.data.surplusDay
            })
          },
          // 添加休假明细
          addVacationDetails() {
              const row = {
                id: undefined,
                vacationId: undefined,
                vacationType: undefined,
                remainDay: undefined,
                vacationDay: undefined
              }
            if (!(this.form.oaVacationDetails instanceof Array)) {
              this.$set(this.form, 'oaVacationDetails', [])
            }
            this.$nextTick(() => {
              this.form.oaVacationDetails.push(row)
            })
          },
          // 删除休假明细
          delVacationDetails(index) {
            this.form.oaVacationDetails.splice(index, 1)
          },
          vacationTypeChange(row) {
            var count = 0
            for (let i = 0; i < this.form.oaVacationDetails.length; i++) {
              if (this.form.oaVacationDetails[i].vacationType === row.vacationType) {
                count++
              }
            }
            if (count > 1) {
              this.msgError(this.$t('同一休假类型只能选择一次'))
              row.vacationType = undefined
              return
            }
            if (!this.form.dateRange[0]) {
              this.msgError(this.$t('请先选择休假时间'))
              row.vacationType = undefined
              return
            }
            const params = {
              applicant: this.form.applicant,
              vacationType: row.vacationType,
              applicationTime: this.parseTime(this.form.dateRange[0], '{y}-{m}-{d}')
            }
            vacationDay(params).then(response => {
              row.remainDay = response.data.remainDay
              row.lastYearSurplusDays = response.data.lastYearSurplusDays
            })
          },
          vacationDayChange(row) {
            if (row.vacationDay < 0) {
              this.msgError(this.$t('休假申请天数不能为负数'))
              return false
            } else {
              if (row.vacationDay > row.remainDay) {
                this.msgError(this.$t('休假申请天数不能超过剩余天数'))
                return false
              } else {
                return true
              }
            }
          },
          changeName() {
            getUser(this.form.applicant).then(response => {
              this.$set(this.form, 'postIds', response.datas.postIds)
              this.$set(this.form, 'deptId', response.data.deptId)
              this.$set(this.form, 'phone', response.data.phonenumber)
            })
          }
        }
    }
</script>
